<?php

namespace app\admin\service\dev;

use app\admin\model\dev\Field as FieldModel;
use app\admin\model\admin\I18n as I18nModel;
use app\admin\service\common\SqlProcessService;
use app\admin\validate\dev\Field as FieldValidate;
use app\admin\service\admin\I18nService;
use think\exception\ValidateException;
use think\facade\Config;
use think\facade\Db;
use think\facade\Lang;
use think\facade\Log;
use think\helper\Str;

class FieldService
{

    /**
     * 【新方法】获取动态选项数据，支持远程搜索、分页和占位符级联
     *
     * @param int $menuId 菜单ID
     * @param string $fieldName 字段名
     * @param string $query 搜索关键字
     * @param int $page 当前页码
     * @param int $pageSize 每页数量
     * @param array $cascadeParams 级联参数 [field_name => value]
     * @return array
     * @throws \Exception
     */
    public static function getDynamicOptions(
        int    $menuId,
        string $fieldName,
        string $query = '',
        int    $page = 1,
        // int $pageSize = 20,
        array  $cascadeParams = []
    ): array
    {
        // 1. 获取字段配置和原始SQL
        $fieldInfo = FieldModel::where('menu_id', $menuId)
            ->where('field', $fieldName)
            ->json(['config'])
            ->find();

        if (!$fieldInfo) {
            return ['list' => [], 'total' => 0, 'current_page' => $page, 'last_page' => 0];
        }

        $rawSql = $fieldInfo->config['item_options'] ?? null;
        if (empty($rawSql)) {
            return ['list' => [], 'total' => 0, 'current_page' => $page, 'last_page' => 0];
        }

        // 2. 占位符替换 (级联逻辑)
        $processedSql = self::applyCascadePlaceholders($rawSql, $cascadeParams);

        // 3. 检查是否所有占位符都被替换
        if (preg_match('/\{\$(.*?)\}/', $processedSql)) {
            // 仍存在未替换的占位符，说明上游级联值缺失，返回空结果
            return ['list' => [], 'total' => 0, 'current_page' => $page, 'last_page' => 0];
        }

        // 4. 获取数据库连接信息
        $menuInfo = Db::name('dev_menu')->find($menuId);
        $connect = $menuInfo['connect'] ?? 'mysql';
        $permission = $fieldInfo->config['is_permission'] ?? false; // 假设配置中定义是否需要数据权限
        // 无需生成代码
        $searchField = $fieldInfo->config['remote_search_field'] ?? 'label';
        // 无需生成代码
        $pageSize = $fieldInfo->config['remote_page_size'] ?? 10;

        // 5. 调用SqlProcessService处理搜索、分页和执行
        $sqlProcessService = new SqlProcessService();
        $result = $sqlProcessService->executeDynamicSql(
            $processedSql,
            $query,
            $searchField,
            $page,
            $pageSize,
            $permission,
            $connect
        );

        // 6. 格式化并返回
        return $result;
    }

    /**
     * 应用级联占位符替换
     * @param string $sql 原始SQL模板
     * @param array $params 级联参数
     * @return string 替换后的SQL
     */
    protected static function applyCascadePlaceholders(string $sql, array $params): string
    {
        return preg_replace_callback('/\{\$(.*?)\}/', function ($matches) use ($params) {
            $fieldName = $matches[1];
            if (isset($params[$fieldName])) {
                return (string)$params[$fieldName];
            }
            return $matches[0];
        }, $sql);
    }

    public static function getMenuOptions($pathinfo): array
    {
        // 获得路由名称
        $firstSlashPos = strpos($pathinfo, '/');
        $firstSegment = ($firstSlashPos !== false) ? substr($pathinfo, 0, $firstSlashPos) : $pathinfo;
        $name = Str::studly(str_replace('.', '-', $firstSegment));
        trace($name, '需要获得字典的菜单路由名');
        // 获得字段数据
        $sqlProcessService = new SqlProcessService();
        $menu_info = Db::name('dev_menu')
            ->where('route_name', $name)
            ->find();
        // 获得键值字典
        $data = FieldService::getKeyValueOption($menu_info);
        // 获得字段中的 SQL
        $sqlListField = FieldService::getSqlOptionsList($menu_info);
        // 获得方法中的 SQL （主要是侧栏的SQL）
        $sqlListAction = ActionService::getSqlOptionsList($menu_info);
        // 合并
        $sqlList = array_merge($sqlListField, $sqlListAction);
        // 生成字典
        foreach ($sqlList as $key => $_data) {
            if (
                $_data['is_permission'] ||
                str_contains(strtoupper($_data['sql']), 'CREATE_ID') ||
                str_contains(strtoupper($_data['sql']), 'CREATE_DEPT')
            ) {
                $data[$key] = $sqlProcessService->parseSqlToDict($_data['sql'], true, $menu_info['connect']);
            } else {
                $data[$key] = $sqlProcessService->parseSqlToDict($_data['sql'], false, $menu_info['connect']);
            }
        }
        return $data;
    }

    /**
     * 添加字段
     * @param array $post
     * @return mixed
     * @throws \Exception
     */
    public static function addField(array $post): mixed
    {
        try {
            $menu_info = Db::name('dev_menu')->find($post['menu_id']);
            // 字段新的数据
            $new_field = [
                'field' => $post['field'],
                'field_type' => $post['config']['field_type'],
                'field_length' => $post['config']['field_length'],
                'field_index' => $post['config']['field_index'],
                'field_constraint' => $post['config']['field_constraint'],
                'field_default' => $post['config']['field_default'],
            ];
            // 找到新字段应该被添加到哪个字段之后
            $after_field_record = FieldModel::where('menu_id', '=', $post['menu_id'])
                ->whereRaw("config->>'$.create_field' = 'create'")
                ->where('sort', '<', 100)
                ->order('sort', 'desc')
                ->find();
            $after_field_name = $after_field_record ? $after_field_record['field'] : null;

            if ($post['config']['create_field'] === 'create') {
                // 同步到数据库，如果失败则删除字段
                $result = DatabaseService::createOrUpdateTableField($menu_info, $after_field_name, $new_field);
                if (!$result) {
                    DatabaseService::deleteField($menu_info, $new_field['field']);
                }
            }
            // 开启事务
            Db::startTrans();
            // 获取排序号
            $maxSort = FieldModel::where('menu_id', $post['menu_id'])
                ->where('sort', '<', 100)
                ->max('sort');
            $post['sort'] = $post['sort'] ?? $maxSort + 1;
            // 添加字段信息
            $field_info = FieldModel::create($post);
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回退事务
            Db::rollback();
            // 删除数据表的字段
            if ($post['config']['form_post']) {
                DatabaseService::deleteField($menu_info, $new_field['field']);
            }
            throw $e;
        }
        // 事务成功后，再执行无法回滚的操作
        try {
            if ($field_info) {
                // 更新翻译数据
                I18nService::asyncTranslationData($post['key'], $post['translations']);
            }
        } catch (\Exception $langException) {
            trace('字段添加成功，但异步更新翻译数据失败');
            trace(['field_id' => $field_info->id, 'key' => $post['key'], 'error' => $langException->getMessage()], 'debug');
        }

        return $field_info ? $field_info->id : null;
    }

    /**
     * 修改字段
     * @param array $post
     * @return true
     * @throws \Exception
     */
    public static function updateField(array $post): bool
    {
        try {
            // 验证数据
            validate(FieldValidate::class)->scene('update')->check($post);
            // 查询旧的字段信息
            $field_info = FieldModel::findOrFail($post['id'])->toArray();

            // trace($field_info,'原字段信息');
            // 旧字段的所属菜单
            $menu_info = Db::name('dev_menu')->find($post['menu_id']);
            // 新的字段的配置
            $new_field = [
                'field' => $post['field'],
                'field_type' => $post['config']['field_type'],
                'field_length' => $post['config']['field_length'],
                'field_index' => $post['config']['field_index'],
                'field_constraint' => $post['config']['field_constraint'],
                'field_default' => $post['config']['field_default'],
                'field_comment' => $post['title'],
            ];
            // 旧的字段的配置
            $old_field = [
                'field' => $field_info['field'],
                'field_type' => $field_info['config']['field_type'],
                'field_length' => $field_info['config']['field_length'],
                'field_index' => $field_info['config']['field_index'],
                'field_constraint' => $field_info['config']['field_constraint'],
                'field_default' => $field_info['config']['field_default'],
                'field_comment' => $field_info['title'],
            ];
            // 找到字段位置
            $after_field_record = FieldModel::where('menu_id', '=', $menu_info['id'])
                ->whereRaw("config->>'$.create_field' = 'create'")
                ->where('sort', '<', $field_info['sort']) // 找到排序在它之前的字段
                ->order('sort', 'desc')
                ->find();
            $after_field_name = $after_field_record ? $after_field_record['field'] : '';
            // 如果更新id字段，则可能会找不到一个前面的字段
            // trace($after_field_record,'原字段信息');

            // 执行数据库表结构变更
            $result = DatabaseService::createOrUpdateTableField($menu_info, $after_field_name, $new_field, $old_field);
            if (!$result) {
                return false;
            }
            // 开启事务
            Db::startTrans();
            // 如果成功，再更新元数据
            FieldModel::update($post, ['id' => $post['id']]);
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回退事务
            Db::rollback();
            trace([
                'menu_id' => $post['menu_id'] ?? 'N/A',
                'field' => $post['field'] ?? 'N/A',
                'error_message' => $e->getMessage(),
                'trace' => $e->getTraceAsString() // 在开发环境中记录堆栈信息
            ], 'debug');
            throw $e;
        }

        // 事务成功后，再执行无法回滚的操作
        try {
            // 更新字段对应多语言数据
            I18nService::asyncTranslationData($post['key'], $post['translations']);
        } catch (\Exception $langException) {
            trace('字段更新成功，但异步更新翻译数据失败');
            trace([
                'field_id' => $post['id'],
                'key' => $post['key'],
                'error' => $langException->getMessage()
            ], 'debug');
        }

        return true;
    }


    /**
     * 根据字段id数组，删除字段
     * @param $ids
     * @return void
     * @throws \Exception
     */
    public static function deleteFields($ids): void
    {
        // 处理空数组入参，避免无效操作
        if (empty($ids)) {
            return;
        }

        // 查询出所有相关数据
        $fields_to_delete = FieldModel::whereIn('id', $ids)->select()->toArray();
        if (empty($fields_to_delete)) {
            return; // 没有找到任何要删除的字段
        }

        // 准备待删除的语言键
        $lang_keys_to_delete = array_column(
            array_filter($fields_to_delete, fn($field) => $field['buildin'] != 1),
            'key'
        );

        try {
            // 开启事务
            Db::startTrans();
            // 删除字段(字段改名)
            DatabaseService::renameField($ids);
            // 删除字段信息
            FieldModel::destroy($ids);
            // 删除语言数据
            if (!empty($lang_keys_to_delete)) {
                I18nModel::whereIn('key', $lang_keys_to_delete)->delete();
            }
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回退事务
            Db::rollback();
            trace([
                'field_ids' => $ids,
                'error_message' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ], 'debug');
            throw $e;
        }
    }

    /**
     * 获得SQL数据源字段及SQL的列表
     * @param $menu_info
     * @return array
     */
    public static function getSqlOptionsList($menu_info): array
    {
        if (!$menu_info) {
            trace("尝试获取不存在的菜单SQL选项列表", ['menuName' => $menu_info['route_name']]);
            return [];
        }
        $prefix = Config::get("database.connections.{$menu_info['connect']}.prefix");
        $sqlList = FieldModel::field('field,config')
            ->where('menu_id', $menu_info['id'])
            ->where('config->item_options_type', 'sql')
            ->whereRaw("(json_extract(`config`, '$.remote_enabled') IS NULL OR json_unquote(json_extract(`config`, '$.remote_enabled')) = '0')")
            ->whereNotNull('config->item_options')
            ->select()
            ->toArray();
        $result = [];
        foreach ($sqlList as $item) {
            $result[$item['field']] = [
                'is_permission' => isset($item['config']['is_permission']) && $item['config']['is_permission'] == 1,
                'sql' => (new SqlProcessService())->addTablePrefix($item['config']['item_options'], $prefix)
            ];
        }

        return $result;
    }

    /**
     * 获得SQL数据源字段及SQL的列表
     * @param $menu_info
     * @return array
     */
    public static function getKeyValueOption($menu_info)
    {
        if (!$menu_info) {
            trace("尝试获取不存在的菜单选项列表", ['menuName' => $menu_info['route_name']]);
            return []; // 如果菜单不存在，返回空数组，防止后续代码出错
        }
        $cache = 60;
        // 用户自定义固定选项数据
        $keyValueList = FieldModel::field('field,config')
            ->where('menu_id', $menu_info['id'])
            ->whereRaw("config->>'$.item_options_type' = 'key_value'")
            ->whereRaw("config->>'$.item_options' IS NOT NULL AND config->>'$.item_options' != ''")
            ->cache($cache) // 缓存60秒
            ->select()->toArray();

        $result = [];
        foreach ($keyValueList as $keyValue) {
            $result[$keyValue['field']] = process_items_recursively($keyValue['config']['item_options']);
        }

        return $result;
    }

    /**
     * 根据菜单ID，删除此菜单的所有字段
     * @param $menu_id
     * @return void
     * @throws \Exception
     */
    public static function deleteMenuFields($menu_id): void
    {
        // 一次性查询出所有需要处理的字段信息
        $all_fields = FieldModel::where('menu_id', $menu_id)->select()->toArray();

        // 如果该菜单下没有任何字段，直接返回，避免空操作
        if (empty($all_fields)) {
            return;
        }

        // 在内存中准备好需要操作的数据
        $field_ids_to_delete = array_column($all_fields, 'id');

        $lang_keys_to_delete = array_column(
            array_filter($all_fields, fn($field) => $field['buildin'] != 1),
            'key'
        );

        try {
            // 开启事务
            Db::startTrans();

            // 删除字段元数据
            if (!empty($field_ids_to_delete)) {
                FieldModel::destroy($field_ids_to_delete);
            }

            // 3.3. 删除对应的多语言键
            if (!empty($lang_keys_to_delete)) {
                I18nModel::whereIn('key', $lang_keys_to_delete)->delete();
            }

            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回退事务
            Db::rollback();
            trace([
                'menu_id' => $menu_id,
                'error_message' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ], 'debug');
            throw $e;
        }
    }


    /**
     * 获得搜索方法的默认字段
     * 数据库字段名默认小写下划线命名
     * @param $menuName
     * @return array
     */
    public static function getIndexFields($menuName, $alias = null): array
    {
        try {
            $menuId = Db::name('dev_menu')
                ->where('route_name', $menuName)
                ->cache('menu_' . $menuName, 60) // 缓存60秒
                ->value('id');

            // 处理菜单不存在的情况
            if (!$menuId) {
                trace('尝试为不存在的菜单获取索引字段', ['menuName' => $menuName]);
                return [];
            }

            $fieldList = Db::name('dev_field')
                ->json(['config'])
                ->whereRaw("config->>'$.grid_visible' <> 'disable'")
                ->whereRaw("config->>'$.create_field' = 'create'")
                ->where('menu_id', $menuId)
                ->whereNull('delete_time')
                ->order('sort asc')
                ->column('field');


            if ($alias && !empty($fieldList)) {
                $fieldList = array_map(function ($item) use ($alias) {
                    return $alias . '.' . $item;
                }, $fieldList);
            }
            return $fieldList;
        } catch (\Exception $e) {
            Log::wirte([
                'menuName' => $menuName,
                'alias' => $alias,
                'error_message' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ], 'debug');
            throw $e;
        }

    }

    /**
     * 获得数据操作方法的默认字段
     * DML: add,update,detail,delete
     * 数据库字段名默认小写下划线命名
     * @param string $menuName
     * @param string|null $dml
     * @return mixed
     */
    public static function getDmlFields(string $menuName, string $dml = null): mixed
    {
        try {
            $menuInfo = Db::name('dev_menu')
                ->where('route_name', $menuName)
                ->cache(60) // 缓存60秒
                ->find();

            if (!$menuInfo) {
                trace('尝试为不存在的菜单获取DML字段', ['menuName' => $menuName]);
                return [];
            }

            // trace($menuInfo,'$menuInfo');
            // 默认情况下id,create_time,update_time,delete_time字段不需要前端提交
            // add 新增数据的时候以字段的 post 状态为准
            if ($dml === 'add') {
                $fieldList = Db::name('dev_field')
                    ->json(['config'])
                    ->whereRaw("config->>'$.form_post' = 1")
                    ->where('menu_id', $menuInfo['id'])
                    ->whereNull('delete_time')
                    ->order('sort asc')
                    ->column('field');
            } else if ($dml === 'update') {
                // 更新需要提交主键字段
                $fieldList = Db::name('dev_field')
                    ->json(['config'])
                    ->whereRaw("config->>'$.form_post' = 1")
                    ->where('menu_id', $menuInfo['id'])
                    ->whereNull('delete_time')
                    ->order('sort asc')
                    ->column('field');
                array_unshift($fieldList, $menuInfo['primary_key']);
            } else if ($dml === 'detail') {
                // 查看详情，可查看创建，修改时间
                $fieldList = Db::name('dev_field')
                    ->json(['config'])
                    ->whereRaw("config->>'$.create_field' <> 'none'")
                    ->whereRaw("config->>'$.field_belong' = 'null'")
                    ->where('menu_id', $menuInfo['id'])
                    ->whereNull('delete_time')
                    ->order('sort asc')
                    ->column('field');
                array_unshift($fieldList, $menuInfo['primary_key']);
                array_push($fieldList, 'create_time', 'create_id', 'update_time');
            } else {
                throw new ValidateException('未设置操作类型');
            }

            return $fieldList;
        } catch (\Exception $e) {
            throw new ValidateException($e->getMessage());
        }

    }

    /**
     * 获得前端搜索表单的字段配置
     * 字段配置，以前端代码优先，如果前端代码修改为未定义，则使用后端配置
     * 数据库字段名默认小写下划线命名
     * @param $menuName
     * @return array
     */
    public static function getSearchFields($menuName): array
    {
        try {
            // 获取语言代码（安全处理）
            $langCode = Lang::getLangSet();

            // 1. 获取菜单信息（带缓存）
            $menuId = Db::name('dev_menu')
                ->where('route_name', $menuName)
                ->cache(60) // 缓存60秒
                ->value('id');

            // trace($menuId,'[FieldService] 获取菜单信息');

            // 菜单不存在直接返回
            if (!$menuId) {
                return [];
            }
            $fieldList = Db::name('dev_field')->alias('a')
                ->leftJoin('admin_i18n b', "a.key = b.key AND b.lang_code = :code")
                ->field('a.id, a.field, a.title, a.config, b.value AS lang_value')
                ->where('menu_id', $menuId)
                ->whereRaw("a.config->>'$.grid_search' <> 'disable'")
                ->whereNull('a.delete_time')
                ->bind(['code' => $langCode])
                ->order('a.sort asc')
                ->select()->toArray();

            // trace($fieldList,'$fieldList');

            $formColumns = [];
            foreach ($fieldList as $field) {
                // 4. 增强JSON解析健壮性
                if (!isset($field['config'])) continue;

                $config = is_string($field['config'])
                    ? json_decode($field['config'], true)
                    : $field['config'];

                $formColumns[] = [
                    'field' => $field['field'],
                    'title' => $field['lang_value'] ?? $field['title'],
                    'folding' => true,
                    'resetValue' => null,
                    'itemRender' => self::getSearchFormItemRender($config)
                ];
            }
            // 获取查询字段数据
            $fieldDatas = Db::name('dev_field')
                ->where('menu_id', $menuId)
                ->whereRaw("config->>'$.grid_search' <> 'disable'")
                ->whereNull('delete_time')
                ->order('sort asc')
                ->column('field');

        } catch (\Exception $e) {
            throw new ValidateException($e->getMessage());
        }
        return ['data' => $fieldDatas, 'items' => $formColumns];
    }


    /**
     * 获得Vxe-grid数据表的列的配置
     * 以前端代码优先，如果前端代码修改为未定义，则使用后端配置
     *  数据库字段名默认小写下划线命名
     * @param $menuName
     * @return array
     */
    public static function getGridColumnConfig($menuName): array
    {
        try {
            // 获取语言代码（安全处理）
            $langCode = Lang::getLangSet();

            // 1. 获取菜单信息（带缓存）
            $menuId = Db::name('dev_menu')
                ->where('route_name', $menuName)
                ->cache(60) // 缓存60秒
                ->value('id');

            // 菜单不存在直接返回
            if (!$menuId) {
                return [];
            }

            // 2. 查询字段配置（参数绑定+精简字段）
            $gridField = Db::name('dev_field')->alias('a')
                ->leftJoin('admin_i18n b', "a.key = b.key AND b.lang_code = :code")
                ->field('a.id, a.field, a.title, a.config, b.value AS lang_value')
                ->where('a.menu_id', $menuId)
                ->whereRaw("a.config->>'$.grid_visible' <> 'disable'")
                ->whereNull('a.delete_time')
                ->bind(['code' => $langCode])
                ->order('a.sort asc')
                ->select()
                ->toArray();

            $columns = [];
            foreach ($gridField as $field) {
                // 4. 增强JSON解析健壮性
                if (!isset($field['config'])) continue;

                $config = is_string($field['config'])
                    ? json_decode($field['config'], true)
                    : $field['config'];

                if (empty($config)) {
                    continue;
                }

                $column = [
                    'title' => $field['lang_value'] ?? $field['title'],
                    'field' => $field['field'],
                    'visible' => ($config['grid_visible'] ?? '') !== 'hidden'
                ];

                // 5. 条件赋值避免空值覆盖
                if (!empty($config['grid_width'])) {
                    $column['width'] = (int)$config['grid_width']; // 类型转换
                }

                if (isset($config['grid_align'])) {
                    $column['align'] = $config['grid_align'];
                }

                // 生成默认渲染、编辑渲染
                $render = self::getColumnRender($config, $field, $menuName);
                if ($render) {
                    $key = $config['grid_editable'] ? 'editRender' : 'cellRender';
                    $column[$key] = $render;
                }

                $columns[] = $column;
            }

            return $columns;
        } catch (\Exception $e) {
            throw new ValidateException($e->getMessage());
        }
    }



    ///////////////////////////////////////////////////////////////////////////////

    /**
     * 前端数据表中各种类型字段的渲染方式
     * @param $config
     * @param $field
     * @return array|null
     */
    private static function getColumnRender($config, $field, $menuName): ?array
    {
        $render = null;
        $typeCaseLower = strtolower($config['type']);
        if (in_array($typeCaseLower, ['input', 'textarea', 'input_tag', 'input_number', 'order_sn', 'client_ip', 'random', 'rich_text_editor'])) {
            $render = [
                'name' => 'ElInput',
                'props' => [
                    'clearable' => true,
                ],
            ];
        }
        // 'list_select' 这个组件通过表关联显示选中的数据
        if (in_array($typeCaseLower, ['select', 'radio', 'checkbox', 'switch', 'transfer', 'tree_select'])) {
            if ($config['item_options_type'] === 'dict') {
                $render = [
                    'name' => 'RaDictSelectRender',
                    'code' => $config['item_options'] ?? 'usr_status'
                ];
            }
            if ($config['item_options_type'] === 'sql') {
                $render = [
                    'name' => 'ElSelect',
                    'options' => "dictOption.value.{$field['field']},"
                ];
            }
            if ($config['item_options_type'] === 'key_value') {
                $render = [
                    'name' => 'ElSelect',
                    'options' => $config['item_options'],
                ];
            }
            if ($config['item_multiple'] === 'multiple') {
                $render['multiple'] = true;
            }
        }

        return $render;
    }

    /**
     * 前端搜索表单项的渲染方式
     * @param $config
     * @return array|null
     */
    private static function getSearchFormItemRender($config): ?array
    {
        $render = null;
        $typeCaseLower = strtolower($config['type']);
        // 输入框
        if (in_array($typeCaseLower, ['input', 'textarea', 'input_tag', 'input_number', 'order_sn', 'client_ip', 'random', 'rich_text_editor'])) {
            $render = [
                'name' => 'ElInput',
                'props' => [
                    'clearable' => true,
                ],
            ];
        }
        // 下拉框搜索
        if (in_array($typeCaseLower, ['select', 'radio', 'checkbox', 'switch', 'transfer', 'list_select', 'tree_select'])) {
            $render = [
                'name' => 'RaDictSelectRender',
                'code' => $config['item_options'] ?? 'usr_status',
                'multiple' => false,
                'clearable' => true,
            ];
        }
        // 日期时间
        if (in_array($typeCaseLower, ['datetime', 'create_time', 'update_time'])) {
            $render = [
                'name' => 'ElDatePicker',
                'props' => [
                    'type' => 'daterange',
                    'clearable' => true,
                ]
            ];
        }
        return $render;
    }
}